<template>
  <div style="padding: 0 20px">
    <div class="tip">注:知识类目均可通过拖拽来调整顺序</div>
    <div class="wrap">
      <split-pane
        @resize="resize"
        :min-percent="20"
        :default-percent="20"
        split="vertical"
      >
        <template slot="paneL">
          <!-- 知识库类别 -->
          <div class="paneL" v-loading="category_loading">
            <tree
              ref="tree"
              :activeIndex.sync="activeIndex"
              :data="categorylist"
              @select="categorySelect"
              @drag="categoryDrag"
              @rename="categoryRename"
              @add="categoryAdd"
              @delete="categorydelete"
              @generateAQrCode="categoryGenerateAQrCode"
              @addReviewers="categoryAddReviewers"
            ></tree>
          </div>
        </template>
        <template slot="paneR">
          <!-- 内容 -->
          <div class="paneR" v-if="categorylist.length > 0">
            <div>
              <!-- 查询条件 -->
              <el-form
                @submit.native.prevent
                :model="queryParams"
                ref="queryForm"
                size="small"
                :inline="true"
                label-width="70px"
                v-if="showSearch"
              >
                <el-form-item label="知识标题" prop="title">
                  <el-input
                    v-input-restrict
                    v-model="queryParams.title"
                    placeholder="请输入知识标题"
                    clearable
                    style="width: 200px"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item label="创建人" prop="createName">
                  <el-input
                    v-input-restrict
                    v-model="queryParams.createName"
                    placeholder="请输入创建人"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item>
                  <el-button
                    v-preventReClick
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >搜索</el-button
                  >
                  <el-button
                    v-preventReClick
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                  >
                </el-form-item>
              </el-form>
              <!-- 搜索按钮 -->
              <!-- <el-row :gutter="10" class="mb8">
                <el-col :span="1.5">
                  <el-button
                    v-preventReClick
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    >新增</el-button
                  >
                </el-col>
                <right-toolbar
                  :showSearch.sync="showSearch"
                  @queryTable="getList"
                ></right-toolbar>
              </el-row> -->
              <div class="commonMenu">
                <el-menu
                  :default-active="queryParams.status"
                  @select="status_select"
                  class="el-menu-demo"
                  mode="horizontal"
                >
                  <el-menu-item index="0">正式在用</el-menu-item>
                  <el-menu-item index="1">已停用</el-menu-item>
                </el-menu>
              </div>
              <!-- 表格 -->
              <el-table v-loading="loading" :data="list">
                <el-table-column
                  label="知识标题"
                  show-overflow-tooltip
                  align="center"
                  prop="title"
                />
                <el-table-column width="120" label="封面" align="center" prop="knowledgePic">
        <template slot-scope="scope">
          <el-image
            :src="
              scope.row.knowledgePic
                ? scope.row.knowledgePic
                : 'https://oss.metaxun.com/wx/zy/nocourse.png'
            "
            fit="cover"
            :width="120"
          />
        </template>
      </el-table-column>
                <el-table-column label="排序" align="center" prop="createTime">
                  <template #header>
                    <div class="flexcolcenter flexcen">
                      排序<el-tooltip
                        class="item"
                        effect="dark"
                        placement="bottom"
                      >
                        <i
                          class="el-icon-question shou"
                          style="
                            font-size: 16px;
                            vertical-align: middle;
                            margin-left: 5px;
                          "
                        ></i>
                        <div slot="content">
                          <div>按数字由小到大顺序排列</div>
                        </div>
                      </el-tooltip>
                    </div>
                  </template>
                  <template slot-scope="scope">
                    <div
                      v-if="!scope.row.isEditing"
                      @dblclick="editSort(scope.row)"
                    >
                      {{ scope.row.sort }}
                    </div>
                    <el-input
                      v-else
                      v-model="scope.row.tempSort"
                      @blur="updateSort(scope.row)"
                    />
                  </template>
                </el-table-column>
                <el-table-column
                  label="创建人"
                  show-overflow-tooltip
                  align="center"
                  prop="createName"
                />
                <el-table-column
                  label="创建时间"
                  align="center"
                  prop="createTime"
                >
                  <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  width="220"
                  label="操作"
                  align="center"
                  class-name="small-padding fixed-width"
                >
                  <template slot-scope="scope">
                    <el-button
                      v-preventReClick
                      size="mini"
                      type="text"
                      icon="el-icon-view"
                      @click="handleDetail(scope.row)"
                      >详情</el-button
                    >
                    <el-button
                      v-if="isManager($store.getters.roles)"
                      v-preventReClick
                      size="mini"
                      type="text"
                      icon="el-icon-open"
                      @click="handleSwitch(scope.row)"
                      >{{ scope.row.status == 0 ? "停用" : "启用" }}</el-button
                    >
                    <el-button
                      v-if="
                        scope.row.status == 1 &&
                        (isManager($store.getters.roles) ||
                          isHead($store.getters.roles))
                      "
                      v-preventReClick
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>

              <pagination
                v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"
              />
            </div>
          </div>
          <el-empty
            style="margin-top: 32px"
            v-else
            description="暂无知识点"
          ></el-empty>
        </template>
      </split-pane>
    </div>
    <!-- 添加知识点 -->
    <addKnowledge
      :open.sync="addKnowledge_open"
      :type="addKnowledge_type"
      :id="addKnowledge_id"
      :categoryid="addKnowledge_categoryid"
      @refresh="getList()"
    ></addKnowledge>
    <!-- 专业审核人 -->
    <addProfessional
      :open.sync="addProfessional_open"
      :type="addProfessional_type"
      :categoryid="addProfessional_categoryid"
    ></addProfessional>
  </div>
</template>
  
<script>
import { isManager } from "@/utils/auth";
import {
  getCategoryList,
  postCategory,
  putCategory,
  deleteCategory,
  sortCategory,
} from "@/api/knowledge/category";
import {
  getknowledgeList,
  putknowledge,
  deleteknowledge,
  generateQRCode,
} from "@/api/knowledge/knowledge";
import tree from "./components/tree";
import addKnowledge from "./components/addKnowledge";
import addProfessional from "./components/addProfessional";
import splitPane from "vue-splitpane";

export default {
  components: { splitPane, tree, addKnowledge, addProfessional },
  data() {
    return {
      //
      addProfessional_open: false,
      addProfessional_type: 1,
      addProfessional_categoryid: null,
      //
      addKnowledge_open: false,
      addKnowledge_type: 1,
      addKnowledge_id: null,
      addKnowledge_categoryid: null,
      //
      activeIndex: 0,
      category_loading: false,
      categorylist: [],
      list: [],
      total: 0,
      showSearch: true,
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        categoryId: undefined,
        createName: undefined,
        status: "0",
      },
    };
  },
  watch: {},
  mounted() {
    this.getCategorylist();
  },
  methods: {
    editSort(row) {
      this.$set(row, "isEditing", true);
      this.$set(row, "tempSort", row.sort);
      this.editingRow = row;
    },
    async updateSort(row) {
      this.$set(row, "isEditing", false);
      if (row.tempSort !== row.sort) {
        row.sort = row.tempSort;
        // 在这里可以添加保存修改的逻辑，比如调用接口保存数据
        console.log("在这里可以添加保存修改的逻辑，比如调用接口保存数据", row);
        try {
          let res = await putknowledge({
            knowledgeId: row.knowledgeId,
            sort: row.tempSort,
          });
          if (res.code == 200) {
            this.$message({
              message: "排序成功",
              type: "success",
            });
            this.getList();
          }
        } catch (error) {}
      }
    },
    /* 是否是总部人员*/
    isManager(e) {
      return isManager(e);
    },
    /* 添加知识点 */
    handleAdd() {
      this.addKnowledge_open = true;
      this.addKnowledge_categoryid =
        this.categorylist[this.activeIndex].categoryId;
    },
    /* 删除知识点 */
    handleDelete(row) {
      this.$confirm(`确定删除【${row.title}】吗?此操作不可恢复！`, "删除确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          try {
            let res = await deleteknowledge(row.knowledgeId);
            if (res.code == 200) {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.getList();
            }
          } catch (error) {}
        })
        .catch(() => {});
    },
    /* 停用/启用知识点 */
    async handleSwitch(row) {
      if (row.status == 0) {
        this.$confirm(
          `确认停用【${row.title}】吗？停用后平台用户将无法查看该知识!`,
          "停用确认",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(async () => {
            try {
              let res = await putknowledge({
                knowledgeId: row.knowledgeId,
                status: 1,
              });
              if (res.code == 200) {
                this.$message({
                  message: "停用成功",
                  type: "success",
                });
                this.getList();
              }
            } catch (error) {}
          })
          .catch(() => {});
      } else {
        try {
          let res = await putknowledge({
            knowledgeId: row.knowledgeId,
            status: 0,
          });
          if (res.code == 200) {
            this.$message({ message: "启用成功", type: "success" });
            this.getList();
          }
        } catch (error) {}
      }
    },
    /* 详情 知识点 */
    handleDetail(row) {
      this.addKnowledge_open = true;
      this.addKnowledge_categoryid = null;
      this.addKnowledge_id = row.knowledgeId;
      this.addKnowledge_type = 5;
    },
    /* 获取知识点 */
    async getList() {
      try {
        this.loading = true;
        let res = await getknowledgeList(this.queryParams);
        this.loading = false;
        if (res.code == 200) {
          this.list = res.rows;
          this.total = res.total;
        }
      } finally {
        this.loading = false;
      }
    },
    /* 获取分类列表 并如果有的话获取 第一个分类获取详细*/
    async getCategorylist() {
      try {
        this.category_loading = true;
        let res = await getCategoryList();
        this.category_loading = false;
        if (res.code == 200) {
          this.categorylist = res.rows.map((item) => {
            return { ...item, showRename: false };
          });
          if (this.categorylist.length > 0) {
            this.queryParams.categoryId = this.categorylist[0].categoryId;
            this.getList();
          }
        }
      } finally {
        this.category_loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    resize() {},
    /* 分类拖拽 */
    async categoryDrag(e) {
      let arr = e.map((item, index) => {
        return { categoryId: item.categoryId, sort: index };
      });
      let res = await sortCategory(arr);
    },
    /* 添加分类 */
    async categoryAdd(e) {
      const loading = this.$loading({
        lock: true,
        text: `添加分类中…`,
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      try {
        let res = await postCategory({
          categoryName: `分类${this.categorylist.length + 1}`,
          sort:
            this.categorylist.length > 0
              ? this.categorylist[this.categorylist.length - 1].sort + 1
              : 1,
        });
        loading.close();
        if (res.code == 200) {
          this.categorylist.push({
            categoryId: res.data,
            categoryName: `分类${this.categorylist.length + 1}`,
            showRename: true,
            sort:
              this.categorylist.length > 0
                ? this.categorylist[this.categorylist.length - 1].sort + 1
                : 1,
          });
          this.$refs.tree.inputfoucus();
        }
      } catch (error) {
        console.log(error);
        loading.close();
      }
    },
    /* 删除分类 */
    async categorydelete(data) {
      this.$confirm(
        `确定删除【${data.categoryName}】吗?删除后会同步删除类目下所有知识，请谨慎处理！`,
        "删除确认",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          try {
            let res = await deleteCategory(data.categoryId);
            if (res.code == 200) {
              if (
                this.categorylist[this.activeIndex].categoryId ==
                data.categoryId
              ) {
                this.activeIndex = 0;
                this.getList();
              }
              this.categorylist = this.categorylist.filter(
                (item) => item.categoryId !== data.categoryId
              );
              this.$message({
                message: "删除成功",
                type: "success",
              });
            }
          } catch (error) {}
        })
        .catch(() => {});
    },
    /* 分类重命名 */
    async categoryRename(data) {
      const loading = this.$loading({
        lock: true,
        text: `加载中…`,
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      try {
        let res = await putCategory(data);
        loading.close();
        if (res.code == 200) {
          this.$message({
            message: "重命名成功",
            type: "success",
          });
        }
      } catch (error) {
        loading.close();
      }
    },
    /* 分类选中 */
    async categorySelect(data) {
      this.queryParams.categoryId = data.categoryId;
      this.getList();
    },
    /* 分类生成二维码 */
    async categoryGenerateAQrCode(data) {
      const loading = this.$loading({
        lock: true,
        text: "加载中",
        spinner: "el-icon-loading",
        background: "rgba(255, 255, 255, 0.6)",
      });
      try {
        let res = await generateQRCode(data.categoryId);
        if (res.code == 200) {
          this.$message({
            message: "生成二维码成功",
            type: "success",
          });
          this.getCategorylist();
        }
      } finally {
        loading.close();
      }
    },
    /* 分类添加审核人 */
    categoryAddReviewers(data) {
      this.addProfessional_open = true;
      this.addProfessional_categoryid = data.categoryId;
    },
    /* 状态选择 */
    status_select(e) {
      this.queryParams.status = e;
      this.getList();
    },
  },
};
</script>
  
<style scoped>
.tip {
  font-size: 12px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #999999;
  line-height: 12px;
  margin: 20px 0;
}
.wrap {
  height: calc(100vh - 86px - 52px);
}
.paneL {
  overflow-y: scroll;
  border-right: 1px solid rgb(250, 250, 250);
  height: 100%;
  width: 100%;
}
.paneR {
  height: 100%;
  width: 100%;
}
::v-deep .splitter-pane-resizer.vertical {
  width: 0px;
}
::v-deep .splitter-pane.vertical.splitter-paneR {
  padding-left: 0;
}
::v-deep .splitter-pane.vertical.splitter-paneL {
  padding-right: 0;
}
</style>